package fr.umlv.android.boggle;

import java.io.InputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import fr.umlv.android.boggle.listener.GameListener;
import fr.umlv.android.boggle.listener.LetterEvent;
import fr.umlv.android.boggle.listener.LetterListener;
import fr.umlv.android.boggle.listener.WordFoundListener;
import fr.umlv.android.boggle.model.BoggleModel;
import fr.umlv.android.boggle.model.BoggleModelImpl;
import fr.umlv.android.boggle.model.Letter;

public class GameActivity extends Activity {
    private BoggleModel model;
    private long lastTime=0;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game);
        Resources res = getResources();
        InputStream inputStreamDico = res.openRawResource(R.raw.dico_boggle);
        model = new BoggleModelImpl(inputStreamDico);
        register(model);
        final Chronometer chrono = (Chronometer) findViewById(R.id.gameChronometer);
        chrono.setOnChronometerTickListener(new OnChronometerTickListener() {
			private long nbSecondes;

			@Override
			public void onChronometerTick(Chronometer chronometer) {
				nbSecondes++;
				System.out.println("NB SECONDES =" +nbSecondes);
				if(nbSecondes>=18) {
					GameActivity.this.gameEnded();
					chrono.stop();
				}
				if(nbSecondes==10) {
					chrono.setTextColor(Color.RED);
				}
			}
		});
        final Button startButton = (Button) findViewById(R.id.gameStartButton);
        final Button pauseButton = (Button) findViewById(R.id.gamePauseButton);
 
		
        // si click sur bouton start ou que le mec secoue -> 
        startButton.setOnClickListener(new OnClickListener() {
			private boolean isFirstStart;
			@Override
			public void onClick(View v) {
				if(!model.isRunning()) {
					model.mixGrid();
				}
		        startButton.setEnabled(false);
		        pauseButton.setEnabled(true);
				// restart chrono
		        if(isFirstStart) {
		        	chrono.setBase(SystemClock.elapsedRealtime());
		        } 
		        else {
		        	chrono.setBase(SystemClock.elapsedRealtime() - lastTime);
		        }
		        chrono.start();
		        isFirstStart=false;
			}
		});
        
        pauseButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				pauseButton.setEnabled(false);
				startButton.setEnabled(true);
				chrono.stop();
				lastTime = SystemClock.elapsedRealtime() - chrono.getBase();
		    }
		});
    }

	protected void gameEnded() {
		Intent intent = new Intent(this, GameEndedActivity.class);	
		ArrayList<String> wordsFound = new ArrayList<String>();
		for(int i=0; i<model.countWordsFound(); i++) {
			wordsFound.add(model.getWordFound(i));
		}
		intent.putStringArrayListExtra("wordsFound", wordsFound);
		intent.putExtra("score", model.getScore());
		startActivity(intent);
	}

	private void register(final BoggleModel model) {
        final Word currentWord = new Word(); // letters selected

		// when a letter changed (selected or uneselected)
		model.addLetterListener(new LetterListener() {
	        TextView viewCurrentWord = (TextView) findViewById(R.id.gameCurrentWord);
	        TableLayout grid = (TableLayout) findViewById(R.id.gameGrid);

	        @Override
			public void letterChanged(LetterEvent event) {
	        	if(event.getEventType() == LetterEvent.LETTER_CHANGED) {
	        	// ici changer couleur de la letter 
		        	Letter letter = event.getLetter();
		        	TableRow row = (TableRow) grid.getChildAt(letter.getRow());
		        	Button button = (Button) row.getChildAt(letter.getCol());
		        	if(letter.isSelected()) {
		        		currentWord.addLetter(letter);
		        		button.setTextColor(Color.BLUE);
		        	}
		        	else {
		        		currentWord.remove(letter);
			        	button.setTextColor(Color.BLACK);
		        	}
		        	viewCurrentWord.setText(currentWord.toString());
	        	}
			}
		});
		
		
		// when a word is find
		model.addWordFoundListener(new WordFoundListener() {
	        LinearLayout wordsFound = (LinearLayout) findViewById(R.id.gameWordsFound);
	        TextView viewCurrentWord = (TextView) findViewById(R.id.gameCurrentWord);
	        TextView viewScore = (TextView) findViewById(R.id.gameScoreView);
	        	        
			@Override
			public void newWordFound(String word) {
		        TextView text = new TextView(GameActivity.this);
		        View viewBar = new View(GameActivity.this);
		        viewBar.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 1));
		        viewBar.setBackgroundColor(Color.GRAY);
		        text.setText(word);
				wordsFound.addView(viewBar, 0);
		        wordsFound.addView(text, 0);
	        	viewCurrentWord.setText(currentWord.toString());
	        	viewScore.setText(String.valueOf(model.getScore()));
			}
		});
		
		// when a game start and over
		model.addGameListener(new GameListener() {
			@Override
			public void gameStarted() {
				//CountDownTimer timer = new DownTimerGame();
		        TableLayout grid = (TableLayout) findViewById(R.id.gameGrid);
		        for(int i=0; i<model.countRow(); i++) {
		        	TableRow row = (TableRow) grid.getChildAt(i);
		        	for(int j=0; j<model.countCol(); j++) {
			        	Button button = (Button) row.getChildAt(j);
			        	final Letter letter = model.getLetter(i, j);
						System.out.println("I ="+i  +", J="+j);
			        	button.setText(Character.toString(letter.getChar()));
			        	button.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								model.selectLetter(letter);
							}
						});
		        	}		        	
		        }
			}
		});
	}
}
